package com.yicong.ants.ui.me.account;

import android.graphics.Color;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cchao.simplelib.core.JsonHelper;
import com.cchao.simplelib.core.Logs;
import com.cchao.simplelib.core.RxBus;
import com.cchao.simplelib.core.RxHelper;
import com.cchao.simplelib.core.UiHelper;
import com.cchao.simplelib.ui.activity.BaseStatefulActivity;
import com.cchao.simplelib.util.StringHelper;
import com.geetest.onelogin.OneLoginHelper;
import com.geetest.onelogin.config.AuthRegisterViewConfig;
import com.geetest.onelogin.config.OneLoginThemeConfig;
import com.geetest.onelogin.config.UserInterfaceStyle;
import com.geetest.onelogin.listener.AbstractOneLoginListener;
import com.yicong.ants.Constants;
import com.yicong.ants.R;
import com.yicong.ants.bean.account.OneLoginBean;
import com.yicong.ants.bean.account.UserBean;
import com.yicong.ants.bean.base.RespBean;
import com.yicong.ants.databinding.LoginActivityBinding;
import com.yicong.ants.manager.AppHelper;
import com.yicong.ants.manager.UserManager;
import com.yicong.ants.manager.ad.EventHelper;
import com.yicong.ants.manager.config.ZzConfigs;
import com.yicong.ants.manager.http.RetrofitHelper;
import com.yicong.ants.utils.DeviceUtils;
import com.yicong.ants.utils.InputCheckUtils;
import com.yicong.ants.utils.KeyBoardUtils;
import com.yicong.ants.utils.StringUtils;
import com.zx.sdk.util.ConfigHelper;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import io.reactivex.Observable;

/**
 * 登录页面
 */
public class LoginActivity extends BaseStatefulActivity<LoginActivityBinding> implements View.OnClickListener {
    private boolean sendCode;
    private int time = 60;
    EditText edSecurityCode;
    EditText edPhoneNumber;
    TextView tvSecurityCode;

    @Override
    protected int getLayout() {
        return R.layout.login_activity;
    }

    @Override
    protected void initEventAndData() {
        AppHelper.transStatus(getWindow());
        edSecurityCode = mDataBind.edSecurityCode;
        edPhoneNumber = mDataBind.mobile;
        tvSecurityCode = mDataBind.tvSecurityCode;
        initViews();
//        initProtocol();
        mDataBind.setClick(this);
        requestOneKey();
    }

    private void requestOneKey() {
        showProgress();
/*        View view = mLayoutInflater.inflate(R.layout.login_verify_code_field, null, false);
        AuthRegisterViewConfig veryLogin = new AuthRegisterViewConfig.Builder()
            .setView(view)
            .setCustomInterface(context -> {
                OneLoginHelper.with().dismissAuthActivity();
                hideProgress();
            })
            .setRootViewId(AuthRegisterViewConfig.RootViewId.ROOT_VIEW_ID_BODY)
            .build();*/

        OneLoginThemeConfig oneLoginThemeConfig = new OneLoginThemeConfig.Builder()
                .setStatusBar(Color.TRANSPARENT, UserInterfaceStyle.LIGHT, true)
                .setAuthNavTextView("", 0, 0, false, "", 0, 0)
                .setLogoImgView("", 0, 0, false, 0, 0, 0)
                .setNumberView(getResources().getColor(R.color.new_text_color_1), 31, 168, 0, 0)
                .setSwitchView("", 0, 0, true, 0, 0, 0)
                .setAuthNavReturnImgView("btn_common_arrowsix", 15, 15, false, 20)
                .setLogBtnLayout("btn_common_longone", "btn_common_longone", 268, 48, 296, 0, 0)
                .setSloganView(getResources().getColor(R.color.new_text_color_3), 11, 358, 0, 0)
                .setPrivacyCheckBox("btn_common_radio_notclicked", "btn_common_radio_click", false, 26, 26)
                .setPrivacyClauseView(getResources().getColor(R.color.new_text_color_1), getResources().getColor(R.color.new_primary_red), 13)
                .setPrivacyClauseTextStrings("已阅读并同意",
                        "隐私政策", "https://api.yctourism.com/api/v2/web/privacy", "",
                        "和", "用户协议", "https://api.yctourism.com/api/v2/web/agreement", "",
                        "和", "", "", "并使用本机号码登录")
                .build();

        ImageView view = new ImageView(this);
        view.setImageResource(R.mipmap.logo_login);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params.addRule(RelativeLayout.CENTER_VERTICAL);
        params.addRule(RelativeLayout.ALIGN_PARENT_END);
        params.setMarginEnd(UiHelper.dp2px(14));
        view.setLayoutParams(params);
        AuthRegisterViewConfig logoLoginViewConfig = new AuthRegisterViewConfig.Builder()
                .setView(view)
                .setRootViewId(AuthRegisterViewConfig.RootViewId.ROOT_VIEW_ID_TITLE_BAR)
                .build();

        View sloganContainerView = LayoutInflater.from(this).inflate(R.layout.login_slogan, null, false);
        sloganContainerView.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        AuthRegisterViewConfig sloganViewConfig = new AuthRegisterViewConfig.Builder()
                .setView(sloganContainerView)
                .setRootViewId(AuthRegisterViewConfig.RootViewId.ROOT_VIEW_ID_BODY)
                .build();

        TextView switchTextView = new TextView(this);
        switchTextView.setText("其他号码登录");
        switchTextView.setGravity(Gravity.CENTER);
        switchTextView.setTextColor(getResources().getColor(R.color.new_text_color_1));
        switchTextView.setCompoundDrawablesWithIntrinsicBounds(null, null, getDrawable(R.mipmap.btn_common_arrow), null);
        switchTextView.setPadding(0, UiHelper.dp2px(214), 0, 0);
        RelativeLayout.LayoutParams switchTextViewLayoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        switchTextViewLayoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
        switchTextView.setLayoutParams(switchTextViewLayoutParams);
        AuthRegisterViewConfig switchTextViewConfig = new AuthRegisterViewConfig.Builder()
                .setView(switchTextView)
                .setCustomInterface(context -> {
                    OneLoginHelper.with().dismissAuthActivity();
                    hideProgress();
                })
                .setRootViewId(AuthRegisterViewConfig.RootViewId.ROOT_VIEW_ID_BODY)
                .build();

        OneLoginHelper.with()
                .addOneLoginRegisterViewConfig("logo", logoLoginViewConfig)
                .addOneLoginRegisterViewConfig("slogan", sloganViewConfig)
                .addOneLoginRegisterViewConfig("switch", switchTextViewConfig)
                .requestToken(oneLoginThemeConfig, new AbstractOneLoginListener() {
                    @Override
                    public void onSwitchButtonClick() {
                        super.onSwitchButtonClick();
                        OneLoginHelper.with().dismissAuthActivity();
                    }

                    @Override
                    public void onResult(JSONObject jsonObject) {
                        if (jsonObject == null) {
                            hideProgress();
                            return;
                        }
                        try {
                            OneLoginBean bean = JsonHelper.toObject(jsonObject.toString(), OneLoginBean.class);
                            if (bean == null) {
                                hideProgress();
                                return;
                            }
                            // status=200 为取号成功，其他返回码请参考返回码章节
                            if (bean.getStatus() != 200) {
                                hideProgress();
                                return;
                            }

                            Map<String, String> map = new HashMap<>();
                            map.put("process_id", bean.getProcess_id());
                            map.put("one_login_token", bean.getToken());
                            map.put("authcode", bean.getAuthcode());
                            addSubscribe(RetrofitHelper.getApis().oneLogin(map)
                                    .compose(RxHelper.toMain())
                                    .subscribe(respBean -> {
                                        hideProgress();
                                        if (respBean.isCodeFail()) {
                                            showToast(respBean.getMsg());
                                            return;
                                        }
                                        OneLoginHelper.with().dismissAuthActivity();
                                        loginSuc(respBean, "登录成功");
                                    }, throwable -> {
                                        hideProgress();
                                        Logs.logException(throwable);
                                        OneLoginHelper.with().dismissAuthActivity();
                                    }));
                        } catch (Exception e) {
                            OneLoginHelper.with().dismissAuthActivity();
                            Logs.logException(e);
                        }
                    }
                });
    }

    @Override
    protected void onLoadData() {

    }

    void toggleLogin(boolean toggle) {
        UiHelper.setVisibleElseGone(mDataBind.referMobileField, !toggle);
        UiHelper.setVisibleElseGone(mDataBind.signGroup, !toggle);
        UiHelper.setVisibleElseGone(mDataBind.tvLogon, toggle);
        mDataBind.agreementTv.setText("已阅读并同意");
        if (toggle) {
            mDataBind.toggleLogin.setText("暂未注册?去注册");
        } else {
            mDataBind.toggleLogin.setText("已有账号?去登录");
        }
    }

    protected void initViews() {
        edSecurityCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                mDataBind.tvLogon.setEnabled(StringHelper.isNotEmpty(edSecurityCode.getText()) && StringHelper.isNotEmpty(edPhoneNumber.getText()));
                mDataBind.signUp.setEnabled(StringHelper.isNotEmpty(edSecurityCode.getText()) && StringHelper.isNotEmpty(edPhoneNumber.getText()));
                if (null != edSecurityCode.getText() && edSecurityCode.getText().length() == 6) {
                    if (!UiHelper.isVisible(mDataBind.signUp)) {
                        KeyBoardUtils.closeKeybord(LoginActivity.this);
                        startLogin();
                    }
                }
            }
        });

        edPhoneNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                mDataBind.tvLogon.setEnabled(StringHelper.isNotEmpty(edSecurityCode.getText()) && StringHelper.isNotEmpty(edPhoneNumber.getText()));
                mDataBind.signUp.setEnabled(StringHelper.isNotEmpty(edSecurityCode.getText()) && StringHelper.isNotEmpty(edPhoneNumber.getText()));
            }
        });
    }

    public void sendVerifyCode(String mobile) {
        if (!InputCheckUtils.isMobile(mobile)) {
            showToast("手机号不合法");
            return;
        }
        Map<String, String> params = new HashMap<>(1);
        params.put("mobile", mobile);
        showProgress();
        Observable<RespBean> disposable;
        if (UiHelper.isVisible(mDataBind.signUp)) {
            disposable = RetrofitHelper.getApis().sendSignVerifyCode(params).compose(RxHelper.toMain());
        } else {
            disposable = RetrofitHelper.getApis().sendLoginVerifyCode(params).compose(RxHelper.toMain());
        }

        addSubscribe(disposable.subscribe(respBean -> {
            hideProgress();
            showToast(respBean.getMsg());
            if ("4009".equals(respBean.code)) {
                toggleLogin(true);
            }

            if (respBean.isCodeFail()) {
                return;
            }

            edSecurityCode.requestFocus();
            sendCode = true;
            tvSecurityCode.setText("60s重发");
            final Timer timer = new Timer();
            TimerTask timerTask = new TimerTask() {
                @Override
                public void run() {
                    UiHelper.runOnUiThread(() -> {
                        if (time <= 0) {
                            sendCode = false;
                            time = 60;
                            tvSecurityCode.setText("获取验证码");
                            timer.cancel();
                            return;
                        }
                        tvSecurityCode.setText(time-- + "S重发");
                    });
                }
            };
            timer.schedule(timerTask, 0, 1000);
        }, RxHelper.getHideProgressConsumer(this)));
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_security_code:
                if (sendCode) {
                    return;
                }
                if (StringUtils.isNull(edPhoneNumber.getText().toString())) {
                    showToast("请先输入手机号");
                    return;
                }
                sendVerifyCode(edPhoneNumber.getText().toString());
                break;
            case R.id.toggle_login:
                toggleLogin(UiHelper.isVisible(mDataBind.signUp));
                break;
            case R.id.back:
                onBackPressed();
                break;
            case R.id.tv_logon:
                startLogin();
                break;
            case R.id.sign_up:
                if (UiHelper.isVisible(mDataBind.signUp)) {
                    applySignUp();
                } else {
                    toggleLogin(false);
                }
                break;
            case R.id.agreement:
                ZzConfigs.toWebActivityByUrlNotLogin(mContext, "ant_agreement");
                break;
            case R.id.privacy:
                ZzConfigs.toWebActivityByUrlNotLogin(mContext, "ant_privacy");
                break;
        }
    }

    boolean checkInput() {
        if (!mDataBind.checkBox.isChecked() && ZzConfigs.mMeShowProtocol) {
            showToast("请先同意用户协议");
            return false;
        }
        String mobile = edPhoneNumber.getText().toString();
        if (StringUtils.isNull(mobile)) {
            showToast("手机号不能为空");
            return false;
        }
        if (StringUtils.isNull(edSecurityCode.getText().toString())) {
            showToast("请输入验证码");
            return false;
        }
        return true;
    }

    private void applySignUp() {
        if (!checkInput()) {
            return;
        }

        Map<String, String> params = new HashMap<>(8);
        params.put("mobile", mDataBind.mobile.getText().toString());
        params.put("code", edSecurityCode.getText().toString());
        params.put("device_token", DeviceUtils.getUniqueId(this));
        params.put("refer_mobile", mDataBind.referMobile.getText().toString());

        showProgress();
        addSubscribe(RetrofitHelper.getApis().signUp(params)
                .compose(RxHelper.toMain())
                .subscribe(respBean -> {
                    hideProgress();
                    if (respBean.isCodeFail()) {
                        showToast(respBean.getMsg());
                        if (respBean.code.equals("4009")) {
                            toggleLogin(true);
                        }
                        return;
                    }
                    loginSuc(respBean, "注册成功");
                }, RxHelper.getHideProgressConsumer(this)));
    }

    private void startLogin() {
        if (!checkInput()) {
            return;
        }

        Map<String, String> params = new HashMap<>(8);
        params.put("mobile", mDataBind.mobile.getText().toString());
        params.put("code", edSecurityCode.getText().toString());
        params.put("device_token", DeviceUtils.getUniqueId(this));

        showProgress();
        addSubscribe(RetrofitHelper.getApis().signIn(params)
                .compose(RxHelper.toMain())
                .subscribe(respBean -> {
                    hideProgress();
                    if (respBean.isCodeFail()) {
                        if (respBean.code.equals("4008")) {
                            toggleLogin(false);
                        }
                        showToast(respBean.getMsg());
                        return;
                    }
                    loginSuc(respBean, "登录成功");
                }, RxHelper.getHideProgressConsumer(this)));
    }

    void loginSuc(RespBean<UserBean> respBean, String tip) {
        EventHelper.reportEvent("login_suc");
        UserManager.updateUserBean(respBean.getData());
        ConfigHelper.loadConfig(true);
        RxBus.get().postEvent(Constants.Event.Login_Suc);
        showToast(tip);
        finish();
        setResult(RESULT_OK);
    }
}
